<?php

namespace App\Http\Controllers\Entity\Column;

use App\Classes\Publish\Publication;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Column\ColumnRequest;
use App\Jobs\Publish\ColumnJob;
use App\Models\Common\CatData\App\Tpl;
use App\Models\Common\CatData\Video\Ccat;
use App\Models\Common\CatData\Video\Vcat;
use App\Models\Common\EntityData\Channel\Ogroup;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\ColumnVasseti;
use App\Models\Operation\ContentTemplate;
use App\Models\Task\Task;
use App\Repositories\Entity\Column\ColumnRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use Validator;

class ColumnController extends Controller
{
    use ModelForm;

    /** @var  ColumnRepository */
    private $columnRepository;

    public function __construct(ColumnRepository $columnRepo)
    {
        $this->columnRepository = $columnRepo;
    }

    /**
     * Display a listing of the Column.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.column.columns.index_header'));
            $content->description(__('entity.column.columns.index_description'));

            $content->body($this->grid($request));
        });
    }

    /**
     * Show the form for creating a new Column.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.column.columns.create_header'));
            $content->description(__('entity.column.columns.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Column in storage.
     *
     * @param ColumnRequest $request
     *
     * @return Response
     */
    public function store(ColumnRequest $request)
    {
        $input = $request->all();

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.column');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $column = $this->columnRepository->create($input);
        if ($column) {
            // 手动添加-添加-中间表
            if (is_array($request->get('ccats'))) {
                $column->ccats()->sync(array_filter($request->get('ccats')));
            }
        }
        Flash::success(__('entity.column.columns.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.columns.index'));

    }

    /**
     * Display the specified Column.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $column = $this->columnRepository->findWithoutFail($id);

        if (empty($column)) {
            Flash::error(__('entity.column.columns.not_found'));

            return redirect(route('entity.column.columns.index'));
        }

        return view('entity.column.columns.show')->with('column', $column);

    }

    /**
     * Show the form for editing the specified Column.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.column.columns.edit_header'));
            $content->description(__('entity.column.columns.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Column in storage.
     *
     * @param  int              $id
     * @param ColumnRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $column = $this->columnRepository->findWithoutFail($id);

        if (empty($column)) {
            Flash::error(__('entity.column.columns.not_found'));

            return redirect(route('entity.column.columns.index'));
        }

        $input = $request->all();

        if (array_key_exists('_file_del_', $input)) {

            $imgUrl       = $column->img;
            $uploadConfig = config('custom.base.upload.column');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];

            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $column->img = null;
                $column->save();
                return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
            }

            return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
        }

        $sValidators = [
            // 'column_no'  => 'required|max:100|unique:columns,column_no,' . $id,
            'name'       => 'required|max:100',
            'title'      => 'max:100',
            'subtitle'   => 'max:100',
            'tpl_id'     => 'required|max:200',
            // 'img'        => 'max:200',
            'online_at'  => 'date',
            'offline_at' => 'date',
            'status'     => 'required',
            'short_desc' => 'max:100',
            'listorder'  => 'required|numeric',
        ];

        $validators = [];

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Column::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'name'       => '名称',
            'title'      => '标题',
            'subtitle'   => '副标题',
            'tpl_id'     => '栏目模板',
            'online_at'  => '上线日期',
            'offline_at' => '下线日期',
            'status'     => '状态',
            'short_desc' => '描述',
            'listorder'  => '排序',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        // 排序
        if ($this->handleOrderable($id, $input)) {
            return response([
                'status'  => true,
                'message' => trans('admin::lang.update_succeeded'),
            ]);
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径

                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.column');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // $rootDir      = config('filesystems.disks.' . $driver . '.root');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                // $rootDir  = config('filesystems.disks.'.$driver.'.root');
                // $fullPath = $dir . '/' . $newImageName;
                // 修改input
                // $input['img'] = $rootDir . $fullPath;

                $input['img'] = $fullPath;

                // 2017/08/22 modify
                // 删除原先存储的图片
                $flag = Storage::disk($driver)->delete($column->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $column = $this->columnRepository->update($input, $id);
        if ($column) {
            // 手动添加-添加-中间表
            if (is_array($request->get('ccats'))) {
                $column->ccats()->sync(array_filter($request->get('ccats')));
            }
        }
        Flash::success(__('entity.column.columns.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.column.columns.index'));
    }

    /**
     * Remove the specified Column from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $column = Column::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->first();
            if (empty($column)) {
                return response()->json(['message' => '只有状态为下线且已下线发布的才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Column::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->pluck('id')->toArray();
            if ($flag = $this->columnRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.column.columns.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $column = $this->columnRepository->findWithoutFail($id);

        if (empty($column)) {
            Flash::error(__('entity.column.columns.not_found'));

            return redirect(route('entity.column.columns.index'));
        }

        // 2017/08/22 modify
        // $imgUrl       = $column->img;
        // $uploadConfig = config('custom.base.upload.column');
        // $driver       = $uploadConfig['driver'];
        // $dir          = $uploadConfig['dir'];

        // 根据配置得到根路径
        // $rootDir = config('filesystems.disks.' . $driver . '.upload');

        // $rootDir  = config('filesystems.disks.'.$driver.'.root');
        // $imgUrl = strchr($imgUrl, $rootDir);

        if ($flag = $this->columnRepository->delete($id)) {

            // 2017/08/22 modify
            // $bool = Storage::disk($driver)->delete($imgUrl);

            return response()->json(['message' => __('entity.column.columns.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Column::class, function (Form $form) {

            $form->display('id', 'ID');
            // $form->text('column_no', '栏目编号');
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'SP')->options($sps);
            $ogroups = Ogroup::pluck('name', 'id');
            $form->select('ogroup_id', '渠道')->options($ogroups);
            $form->textarea('onclick', 'onclick点击事件');
            $form->textarea('onfocus', 'onfocus焦点事件');
            $form->text('restful', 'restful路由');
            $form->textarea('description', '描述');
            // $tpls = Tpl::pluck('name', 'id');
            $contentTemplates = ContentTemplate::pluck('alias', 'id');
            $form->select('content_template_id', '模版')->options($contentTemplates);
            // $Collists = Collist::pluck('name', 'id');
            $ccats = Ccat::pluck('name', 'id');
            $form->multipleSelect('ccats', '分类')->options($ccats);
            $form->image('img', '栏目图片')->removable();
            $form->date('online_at', '上线日期')->default(date('Y-m-d', time()));
            $form->date('offline_at', '下线日期')->default(date('Y-m-d', time()));
            $form->radio('status', '状态')->options([
                'online'  => '上线',
                'offline' => '下线',
                'stop'    => '停用',
            ])->default('offline');
            // 模板推荐类型
            $recommendTypes = [
                0 => 'area',
                1 => 'list0',
                2 => 'list1',
            ];
            // $arrProvinces = Area::provinceByArea()->orderBy('listorder', 'asc')->pluck('alias', 'f_id')->toArray();

            // $form->select('recommend_type_id', '推荐数据类型')->options($recommendTypes)->load('recommend_data_id', route('entity.column.recommend_types.recommend_templates'), 'id', 'name');
            // $form->select('recommend_data_id', '选择数据')->options($contentTemplates);

            $form->text('children_data_href', '子数据链接');
            $form->text('short_desc', '简介');
            $form->textarea('long_desc', '详述');
            $form->number('listorder', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Column::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 状态过滤
            Publication::statusFilter($request->input('status'), $request->input('published'), $grid);

            // //添加按钮
            // if (!\Gate::check('entity.column.columns.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('entity.column.columns.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('entity.column.columns.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('entity.column.columns.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('entity.column.columns.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 表格中的按钮
            $grid->actions(function ($actions) {
                // 编辑数据按钮

                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $id                  = $actions->getKey();
                if (Admin::user()->can('entity.column.columns.edit_asset')) {
                    $url = route('entity.column.columns.edit_asset', ['columns' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="编辑媒资"><i class="fa fa-list"></i></a>');
                }
                // 上线发布按钮
                if ($publish_status === 0 && $online_status === 1 && Admin::user()->can('entity.column.columns.publish_one_or_more')) {
                    $url      = route('entity.column.columns.publish_one_or_more');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                }
                // 下线发布按钮
                if ($publish_down_status === 0 && $online_status === 0 && Admin::user()->can('entity.column.columns.publish_down_one_or_more')) {
                    $url      = route('entity.column.columns.publish_down_one_or_more');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                }
                // 上线按钮
                if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.column.columns.up')) {
                    $url      = route('entity.column.columns.up');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                }
                // 下线按钮
                if ($online_status === 1 && Admin::user()->can('entity.column.columns.down')) {
                    $url      = route('entity.column.columns.down');
                    $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                }
                // 编辑按钮
                if (Admin::user()->cannot('entity.column.columns.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.column.columns.destroy')) {
                    $actions->disableDelete();
                }
                // 只有状态下线的资源才可以编辑,删除
                if ($publish_down_status === 0) {
                    $actions->disableEdit();
                    $actions->disableDelete();
                }
            });

            // 添加按钮
            if (Admin::user()->cannot('entity.column.columns.create')) {
                $grid->disableCreation();
            }

            // 导出按钮
            if (Admin::user()->cannot('entity.column.columns.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.column.columns.progress');
                // 下线发布功能
                if (Admin::user()->can('entity.column.columns.publish_down')) {
                    $url      = route('entity.column.columns.publish_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                }
                // 上线发布功能
                if (Admin::user()->can('entity.column.columns.publish')) {
                    $url      = route('entity.column.columns.publish');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                }
                // 全部下线功能
                if (Admin::user()->can('entity.column.columns.all_down')) {
                    $url      = route('entity.column.columns.all_down');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                }
                // 全部上线功能
                if (Admin::user()->can('entity.column.columns.all_up')) {
                    $url      = route('entity.column.columns.all_up');
                    $function = "upAndDownByAll('$url', '$url2', 'get')";
                    $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                }
                // 过滤按钮
                $tools->append(new \App\Admin\Extensions\Tools\Column\ColumnStatus());
                $tools->append(new \App\Admin\Extensions\Tools\Column\ColumnPublished());
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.column.columns.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // 批量上线按钮
                    if (Admin::user()->can('entity.column.columns.up')) {
                        $batch->add('上线', new \App\Admin\Extensions\Tools\Column\ReleaseColumn('up'));
                    }
                    // 批量下线按钮
                    if (Admin::user()->can('entity.column.columns.down')) {
                        $batch->add('下线', new \App\Admin\Extensions\Tools\Column\ReleaseColumn('down'));
                    }
                    // 批量上线发布按钮
                    if (Admin::user()->can('entity.column.columns.publish_one_or_more')) {
                        $batch->add('上线发布', new \App\Admin\Extensions\Tools\Column\ReleaseColumn('publish'));
                    }
                    // 批量下线发布按钮
                    if (Admin::user()->can('entity.column.columns.publish_down_one_or_more')) {
                        $batch->add('下线发布', new \App\Admin\Extensions\Tools\Column\ReleaseColumn('publishDown'));
                    }
                });
            });

            // $grid->column('column_no', '栏目编号')->sortable();
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable()->editable();
            $grid->column('title', '标题')->sortable()->editable();
            $grid->column('subtitle', '副标题')->sortable()->editable();
            $grid->column('sp.name', 'SP')->sortable();
            $grid->column('ogroup.name', '渠道')->sortable();
            $grid->column('onclick', 'onclick点击事件')->sortable();
            $grid->column('onfocus', 'oncfocus焦点事件')->sortable();
            $grid->column('restful', 'restful路由')->sortable();
            $grid->column('description', '描述')->sortable();

            $grid->column('contentTemplate.alias', '模版')->sortable();
            $grid->ccats('分类')->pluck('name')->label();
            $uploadConfig = config('custom.base.upload.column');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('img', '栏目图片')->image($host);
            $grid->column('short_desc', '简介')->sortable();
            $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();

            $grid->column('children_data_href', '子数据');
            $grid->column('online_at', '上线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('offline_at', '下线日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-red">下线</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-green">上线</span>';
                        break;
                    default:
                        return '未知';
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($this->online_status) {
                    case 0:
                        switch ($this->publish_down_status) {
                            case 0:
                                return '<span class="badge bg-red">下线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">下线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    case 1:
                        switch ($this->publish_status) {
                            case 0:
                                return '<span class="badge bg-red">上线未发布</span>';
                                break;
                            case 1:
                                return '<span class="badge bg-green">上线已发布</span>';
                                break;
                            default:
                                return '未知';
                        }
                        break;
                    default:
                        return '未知';
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 分类
                $tempCcats = Ccat::pluck('name', 'id');
                $filter->where(function ($query) {
                    $input = $this->input;
                    $query->whereHas('ccats', function ($query) use ($input) {
                        $query->where('ccat_id', '=', "{$input}");
                    });

                }, '分类')->select($tempCcats);
                // 状态
                // $aStatus = array(
                //     'online'  => '上线',
                //     'offline' => '下线',
                //     'stop'    => '停用',
                // );
                // $filter->is('status', '状态')->select($aStatus);

                // 编号
                // $filter->like('column_no', '编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 上线时间
                $filter->between('online_at', '上线时间')->datetime();
                // 下线时间
                $filter->between('offline_at', '下线时间')->datetime();
            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.column.columns.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = DB::table('columns as a')
        //     // ->join('subcolumns as b', 'a.id', '=', 'b.column_id')
        //     ->where(['a.online_status' => 0, 'a.publish_down_status' => 1])
        //     ->pluck('a.id')->unique()->count();
        $result = Publication::getTotalNum(new Column(), [
            [['online_status' => 0], 'ID为以下栏目已经上线: '],
            [['publish_down_status' => 1], 'ID为以下栏目还未下线发布: '],
        ], '栏目上线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '栏目上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new ColumnJob(['dispatch', 'up'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.column.columns.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Column(), ['online_status' => 1]);
        $result = Publication::getTotalNum(new Column(), [
            [['online_status' => 1], 'ID为以下栏目还没上线'],
        ], '栏目下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data   = ['task_type' => '栏目下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new ColumnJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.column.columns.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Column(), ['online_status' => 1, 'publish_status' => 0]);
        $result = Publication::getTotalNum(new Column(), [
            [['online_status' => 1], 'ID为以下栏目还未上线: '],
            [['publish_status' => 0], 'ID为以下栏目已经上线发布: '],
        ], '栏目发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data['total_num'] = $total_num;
        // 任务表插入一条记录
        $data   = ['task_type' => '栏目发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        // (new ColumnJob(1, '', $taskid))->handle();exit;
        dispatch(new ColumnJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.column.columns.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Publication::getTotalNum(new Column(), ['online_status' => 0, 'publish_down_status' => 0]);
        $result = Publication::getTotalNum(new Column(), [
            [['online_status' => 0], 'ID为以下栏目还未下线: '],
            [['publish_down_status' => 0], 'ID为以下栏目已经下线发布: '],
        ], '栏目下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        // 任务表插入一条记录
        $data   = ['task_type' => '栏目下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new ColumnJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.column.columns.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 0, 'publish_down_status' => 1]);
                $result = Publication::myfilter(new Column(), $request->ids, [
                    [['online_status' => 0], 'ID为以下栏目已经上线: '],
                    [['publish_down_status' => 1], 'ID为以下栏目还未下线发布: '],
                ], '栏目上线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果栏目的二级栏目为空,不能上线
                // $hasSubcolumnIds = Subcolumn::whereIn('column_id', $ids)->pluck('column_id')->unique();
                $result = Publication::updateMany(new Column(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.column.columns.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 1, 'publish_status' => 0]);
                $result = Publication::myfilter(new Column(), $request->ids, [
                    [['online_status' => 1], 'ID为以下栏目还未上线: '],
                    [['publish_status' => 0], 'ID为以下栏目已经上线发布: '],
                ], '栏目发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data   = ['task_type' => '栏目发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new ColumnJob(['publish'], $ids, $taskid));
                    $url = route('entity.column.columns.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $columns      = Column::whereIn('id', $ids)->with('contentTemplate.contentTemplateType', 'collists', 'ccats', 'subcolumns')->get();
                $column_datas = ColumnJob::makeColumns($columns);
                $result1      = Publication::insertApi('columns', $column_datas);
                $result2      = Publication::updateMany(new Column(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                $content = ($result1 && $result2) ? $content : '发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.column.columns.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 1]);
                $result = Publication::myfilter(new Column(), $request->ids, [
                    [['online_status' => 1], 'ID为以下栏目还没上线'],
                ], '栏目下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Column(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.column.columns.publish_down_one_or_more')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Column(), $request->ids, ['online_status' => 0, 'publish_down_status' => 0]);
                $result = Publication::myfilter(new Column(), $request->ids, [
                    [['online_status' => 0], 'ID为以下栏目还未下线: '],
                    [['publish_down_status' => 0], 'ID为以下栏目已经下线发布: '],
                ], '栏目下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $columnsCount = DB::connection('interface')->table('columns')->whereIn('columnid', $ids)->count();
                if ($columnsCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('columns', 'columnid', $ids);
                } else {
                    $result1 = true;
                }
                // 更新状态
                $result2 = Publication::updateMany(new Column(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? $content : '下线发布失败!']);
        }
    }

    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }

    /**
     * 根据推荐模板类型返回不同的模板数据(如果没有,则返回空数组)
     */
    public function getTemplatesByRecommendType(Request $request)
    {
        $recommendTypeId = $request->get('q');
        $data            = [];

        //  如果推荐模板类型为0, 则获取模板相关数据
        if ($recommendTypeId === '0') {
            $data = ContentTemplate::orderBy('listorder', 'asc')->get(['alias as name', 'id'])->toArray();
            // 如果推荐模板类型为1, 则获取栏目列表数据
        } elseif ($recommendTypeId === '1') {
            $data = Collist::orderBy('listorder', 'asc')->get(['name', 'id'])->toArray();
        } elseif ($recommendTypeId === '2') {
            $data = [
                // [
                //     'id'   => '',
                //     'name' => 'list1数据',
                // ],
            ];
        }
        return array_merge([['id' => '', 'name' => '选择']], $data);
    }

    /**
     * 给一级栏目添加媒资
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editAsset($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('添加媒资'));
            // 分集数据
            $content->row($this->vassetiTab($id));
        });
    }

    // 剧集tab
    public function vassetiTab($id)
    {
        $tab = new Tab();

        $tab->add('编辑点播媒资', $this->editVasseti($id));
        // $tab->add('编辑直播媒资', $this->editVchan($id));
        return $tab;
    }

    /**
     * [编辑点播媒资]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function editVasseti($id)
    {
        // 只能手动调用下函数
        Admin::script('entityColumnColumnAsset();');
        // 分类
        $vcats = Vcat::get(['name', 'id']);
        // 归类数据
        $vcattags = Vcattag::get(['name', 'id']);
        return view('entity.column.column.asset', ['vcats' => $vcats, 'vcattags' => $vcattags, 'column_id' => $id]);
    }

    /**
     * [data 媒资数据]
     * @return [type] [description]
     */
    public function vassetiData(Request $request)
    {

        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 一级栏目id
            $column_id = $request->input('column_id');
            // 收费类型
            $charge_type          = $request->input('charge_type');
            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = Vasseti::onlineStatus()->onlinePublished()->
                where(function ($query) use ($column_id) {
                if (!empty($column_id)) {
                    $query = $query->whereNotIn('id', ColumnVasseti::where(['column_id' => $column_id])->pluck('vasseti_id')->toArray());
                }
            })
                ->count();
            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }

            $data['recordsFiltered'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $column_id) {
                    if (!empty($search_value)) {
                        $query = $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($column_id)) {
                        $query = $query->whereNotIn('id', ColumnVasseti::where(['column_id' => $column_id])->pluck('vasseti_id')->toArray());
                    }
                })->count();

            $data['data'] = Vasseti::onlineStatus()->onlinePublished()->with(['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'])
                ->whereHas('vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->where(function ($query) use ($charge_type) {
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->where(function ($query) use ($search_value, $column_id) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if (!empty($column_id)) {
                        $query = $query->whereNotIn('id', ColumnVasseti::where(['column_id' => $column_id])->pluck('vasseti_id')->toArray());
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();

            return response()->json($data);
        }

        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

    /**
     * 添加单个媒资|多个媒资
     * @param Request $request [description]
     */
    public function addVasseti(Request $request)
    {
        $column_id  = $request->input('column_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果一级栏目已经上线且发布,则不让新增、删除操作
        $data = Column::where('id', '=', $column_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该一级栏目已上线发布,不能添加媒资!', 'status' => false]);
        }

        if (empty($column_id)) {
            return response()->json(['content' => '一级栏目为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量添加
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = ColumnVasseti::where(['column_id' => $column_id, 'vasseti_id' => $value])->first();
                if ($flag) {
                    return response()->json(['content' => '不能重复添加已经存在的媒资!', 'status' => false]);
                } else {
                    $columnVasseti             = new ColumnVasseti();
                    $columnVasseti->column_id  = $column_id;
                    $columnVasseti->vasseti_id = $value;
                    if (!$columnVasseti->save()) {
                        return response()->json(['content' => '添加失败!', 'status' => false]);
                    }
                }
            }
            return response()->json(['content' => '添加成功！', 'status' => true]);
        }

        $flag = ColumnVasseti::where(['column_id' => $column_id, 'vasseti_id' => $vasseti_id])->first();
        if ($flag) {
            return response()->json(['content' => '该媒资已经存在,不能重复添加!', 'status' => false]);
        } else {
            $columnVasseti             = new ColumnVasseti();
            $columnVasseti->column_id  = $column_id;
            $columnVasseti->vasseti_id = $vasseti_id;
            $flag                      = $columnVasseti->save();
            if ($flag) {
                return response()->json(['content' => '添加成功!', 'status' => $flag]);
            } else {
                return response()->json(['content' => '添加失败!', 'status' => $flag]);
            }
        }
    }

    /**
     * 删除单个媒资|多个媒资
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function deleteVasseti(Request $request)
    {
        $column_id  = $request->input('column_id');
        $vasseti_id = $request->input('vasseti_id');

        // 如果一级栏目已经上线且发布,则不让新增、删除操作
        $data = Column::where('id', '=', $column_id)->select(['online_status', 'publish_status'])->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {
            return response()->json(['content' => '该一级栏目已上线发布,不能删除媒资!', 'status' => false]);
        }

        if (empty($column_id)) {
            return response()->json(['content' => '一级栏目为空!', 'status' => false]);
        }
        if (empty($vasseti_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($vasseti_id)) {
            foreach ($vasseti_id as $value) {
                $flag = ColumnVasseti::where(['column_id' => $column_id, 'vasseti_id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = ColumnVasseti::where(['column_id' => $column_id, 'vasseti_id' => $vasseti_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }

    /**
     * [selected 已选的媒资数据]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function selectedVasseti(Request $request)
    {
        if ($request->ajax()) {
            /**
             * 过滤字段
             */
            // 归类
            $vcat = $request->input('vcat');
            // 分类
            $vcattag = $request->input('vcattag');
            // 搜索框的值
            $search_value = $request->input('search_value');
            // 一级栏目的ID
            $column_id = $request->input('column_id');
            // 收费类型
            $charge_type = $request->input('charge_type');

            $data                 = array();
            $data['draw']         = $request->get('draw');
            $start                = $request->get('start') ?: 0;
            $length               = $request->get('length') ?: 10;
            $order                = $request->get('order');
            $columns              = $request->get('columns');
            $search               = $request->get('search');
            $data['recordsTotal'] = ColumnVasseti::whereHas('column', function ($query) use ($column_id) {
                if (!empty($column_id)) {
                    $query = $query->where('id', '=', $column_id);
                }
            })->count();

            if ($order) {
                $orderColumData = $columns[$order[0]['column']]['data'];
            }

            // 排序字段
            $ord = '';
            if (!empty($orderColumData)) {
                $ord = $orderColumData . ' ' . $order[0]['dir'];
            } else {
                $ord = 'id asc';
            }
            $data['recordsFiltered'] = ColumnVasseti::with(['column', 'vasseti', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('column', function ($query) use ($column_id) {
                    if (!empty($column_id)) {
                        $query = $query->where('id', '=', $column_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })->count();

            $data['data'] = ColumnVasseti::with(['column', 'vasseti.vcat', 'vasseti.actors', 'vasseti.directors', 'vasseti.vareas', 'vasseti.vlangs', 'vasseti.vyears', 'vasseti.vcattags'])
                ->whereHas('vasseti.vcat', function ($query) use ($vcat) {
                    if (!empty($vcat)) {
                        $query = $query->where('id', $vcat);
                    }
                })
                ->whereHas('vasseti.vcattags', function ($query) use ($vcattag) {
                    if (!empty($vcattag)) {
                        $query = $query->where('vcattag_id', $vcattag);
                    }
                })
                ->whereHas('column', function ($query) use ($column_id) {
                    if (!empty($column_id)) {
                        $query = $query->where('id', '=', $column_id);
                    }
                })
                ->whereHas('vasseti', function ($query) use ($search_value, $charge_type) {
                    if (!empty($search_value)) {
                        $query->where('name', 'like', '%' . $search_value . '%')
                            ->orWhere('short_desc', 'like', '%' . $search_value . '%');
                    }
                    if ($charge_type == '0' || $charge_type == '1') {
                        $query = $query->where('charge_type', '=', $charge_type);
                    }
                })
                ->skip($start)->take($length)
                ->orderByRaw($ord)
                ->get();
            return response()->json($data);
        }
        return response()->json(['status' => 'error', 'content' => '非法操作']);
    }

}
